package com.project.common.util;

import java.util.Collection;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonUtils {
	
	/**
	 * 将数据集转化为json对象
		{                                                      
			"total":2,                                                      
			"rows":[                                                          
				{"code":"001","name":"Name 1","addr":"Address 11","col4":"col4 data"},         
				{"code":"010","name":"Name 10","addr":"Address 78","col4":"col4 data"}     
			]                                                          
		}
	 * @param totalCount
	 * @param obj
	 * @return
	 */
	public static JSONObject toGridJson(int totalCount,Object obj){
		//如果数据集对象为null做个特殊处理
		if(null==obj){
			JSONObject jsonResult = new JSONObject();
			jsonResult.put("total", totalCount);
			jsonResult.put("rows", new JSONArray());
			return jsonResult;
		}
		if(!Collection.class.isAssignableFrom(obj.getClass())){
			JSONObject jsonResult = new JSONObject();
			jsonResult.put("total", totalCount);
			jsonResult.put("rows", new JSONArray());
			return jsonResult;
		}
		JSONArray jsonArray = JSONArray.fromObject(obj);
		JSONObject jsonResult = new JSONObject();
		jsonResult.put("total", totalCount);
		jsonResult.put("rows", jsonArray);
		return jsonResult;
	}
	
}
